package com.felix.netty;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NioUtil
 *
 * @author xuejinhua
 * @date 2018/10/17 10:48
 */
@Slf4j
public final class NioUtil {

    /**
     * 文件复制
     *
     * @param src 源文件名称
     * @param dst 目标文件名称
     * @return
     * @author xuejinhua
     * @date 2018/10/17 10:55
     * @modify
     */
    public static void copyFile(String src, String dst) {
        try (FileInputStream in = new FileInputStream(new File(src));
             FileOutputStream out = new FileOutputStream(new File(dst))) {
            FileChannel inChannel = in.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            FileChannel outChannel = out.getChannel();
            int bytesRead;
            while ((bytesRead = inChannel.read(byteBuffer)) != -1) {
                System.out.println("Read " + bytesRead);
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()) {
                    outChannel.write(byteBuffer);
                }
                byteBuffer.clear();
            }
        } catch (IOException e) {
            log.error("copy file failure", e.getMessage());
        }
    }

    public static void main(String[] args) {
        copyFile("D:\\temp\\nio\\copy\\account.txt", "D:\\temp\\nio\\copy\\dst.txt");
    }
}
